package api

import (
	"encoding/json"
	"net/http"
	"strings"

	"new_sensitive/internal/ac"
	"new_sensitive/internal/model"
)

// FilterHandler 敏感词过滤处理器
type FilterHandler struct {
	automaton *ac.Automaton
}

// NewFilterHandler 创建敏感词过滤处理器
func NewFilterHandler(automaton *ac.Automaton) *FilterHandler {
	return &FilterHandler{automaton: automaton}
}

// ServeHTTP 处理敏感词过滤请求
func (h *FilterHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 只接受POST请求
	if r.Method != http.MethodPost {
		http.Error(w, "仅支持POST请求："+r.Method, http.StatusMethodNotAllowed)
		return
	}

	// 解析表单数据
	if err := r.ParseForm(); err != nil {
		http.Error(w, "解析表单数据失败", http.StatusBadRequest)
		return
	}

	// 获取文本内容
	text := r.FormValue("text")
	if text == "" {
		http.Error(w, "文本内容不能为空", http.StatusBadRequest)
		return
	}

	// 查找敏感词
	sensitiveWords := h.automaton.Search(text)

	// 过滤文本
	filteredText := text
	highlightText := text
	for _, word := range sensitiveWords {
		filteredText = strings.ReplaceAll(filteredText, word, strings.Repeat("*", len([]rune(word))))
		highlightText = strings.ReplaceAll(highlightText, word, "<span style='color:red'>"+word+"</span>")
	}

	// 构建响应
	resp := model.FilterResponse{
		OriginalText:  text,
		FilteredText:  filteredText,
		HighlightText: highlightText,
		HasSensitive:  len(sensitiveWords) > 0,
	}

	// 返回JSON响应
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		http.Error(w, "响应编码失败", http.StatusInternalServerError)
		return
	}
}
